<template>
  <div>
    <!-- 人脸抓拍 -->
    <van-overlay  class="overlly" v-if="photoVisibles" style="z-index: 999 !important;" :show="photoVisible">
        <div class="photo-start" style="background:white;">
            <div class="wrapper" style="width: 100%;height: 100%;background: #fff;">
                <div :style="'width: ' + screenWidth + 'px; height: ' + clientHeight + 'px;'" >
                    <video id="video" style="transform: rotateY(180deg);"  :width="screenWidth" :height="clientHeight" preload autoplay loop muted playsinline webkik-playsinline="true"></video>
                    <canvas id="canvas" :width="screenWidth" :height="clientHeight" style="display:none;"></canvas>
                </div>
                <div v-if="sumitErrorTips" :style="'width: ' + screenWidth + 'px; height: ' + clientHeight + 'px;'" >
                    <img :src="capImagesUrl" style="width: 100%;"/>
                </div>
            </div>
            <div class="buuton-footer">
              <div class="button-div">
                <van-button type="default"  @click="signOut()" style="margin-right: 10px;">{{$t('circle297')}}</van-button>
                <van-button type="info"  @click="photograph()" style="margin-left: 10px;">{{$t('photo')}}</van-button>
              </div>
            </div>
        </div>
    </van-overlay>
  </div>
</template>

<script>
import {Dialog, Overlay, Button} from 'vant';
import LoginVue from '../login/Login.vue';

export default {
    name: 'faceModal',
    components: {
        [Dialog.Component.name]: Dialog.Component,
        [Overlay.name]: Overlay,
        vanButton: Button
    },
    props: {
        photoVisible: {
            type: Boolean,
            default: false
        },
        randomNode: {
            type: Array,
            default() {
                return [];
            }
        },
        topicIndex: {
            type: Number,
            default: 0
        },
        randomNodeVideo: {
            type: Boolean,
            default: false
        },
        randomNodeCtsId: {
            type: String,
            default: ''
        }
    },
    data() {
        return {
            photoVisibles: true,
            faceStuas: null,
            videoNode: {},
            isPhoto: false,
            video: null,
            canvas: null,
            iosPhoto: false,
            isiOS: null,
            context: '',
            imgSrc: '',
            url: '',
            photoSrc: '',
            screenshotCanvas: null,
            screenWidth: document.documentElement.clientWidth || document.body.clientWidth,
            clientHeight: document.documentElement.clientHeight || document.body.clientHeight,
            capImagesUrl: '',
            sumitErrorTips: false
        };
    },
    mounted() {
        let u = navigator.userAgent;
        //android终端
        let isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1;
        // ios终端;
        this.isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
        if (this.isiOS) {
            this.iosPhoto = true;
        }
    },
    watch: {
        photoVisible(newVal, oldVal) {
            this.photoVisible = newVal;
            this.photoVisibles = newVal;
            if (newVal === true) {
                this.getCompetence();
            }
        },
        randomNode(newVal) {
            this.randomNode = newVal;
        },
        isPhoto(newVal) {
            this.isPhoto = newVal;
        }
    },
    methods: {
        // 退出人脸抓拍
        closePhoto() {
            this.isPhoto = false;
        },
        /** 拍照 **/
        photograph() {
            this.startPhoto();
            this.stopNavigator();
        },
        // 调用摄像头权限
        getCompetence() {
            this.isPhoto = true;
            // if (this.isiOS) {
            //     this.appUpFile();
            // } else {
            this.openPhoto();
            // }
        },
        // ios调用h5plus进行拍照
        appUpFile() {
            let _this = this;
            this.photoVisibles = false;
            // _this.$emit('changeStateVideo');//关闭弹窗，防止退出延迟弹窗出现

            try {
                // const camera = _this.$store.state.config.plus.camera.getCamera(2);
                const camera = window.plus.camera.getCamera(2);
                let cameraPermission = window.plus.navigator.checkPermission('camera');
                if (cameraPermission === 'denied') { //相机权限未获取，请往设置应用程序里面开启权限!
                    window.plus.nativeUI.alert(this.$t('scan_tips_11'), () => {
                        this.$router.go(-1);
                    });
                }
                camera.captureImage(function(path) {
                    // path  为获取拍照照片的url
                    // _this.$store.state.config.plus.io.resolveLocalFileSystemURL(path, async(entry) => {
                    window.plus.io.resolveLocalFileSystemURL(path, async(entry) => {
                        // entry 为获取的文件对象
                        // 图片太大，进行压缩
                        const res = await _this.compressImage(
                            entry.toLocalURL(),
                            entry.name
                        );
                        // 将压缩后的转化为base64格式
                        const url = await _this.showPics(res.target, entry.name);
                        // console.log(url, 'url');
                        const blob = _this.dataURLtoBlob(url);
                        const toFlie = new File([blob], 'qiangzi.png', { type: blob.type, lastModified: Date.now() });
                        const formData = new FormData();
                        formData.append('file', toFlie);
                        _this.$axios.post('/app/api/file', formData).then(res => {
                            _this.url = res.data.url;
                            _this.witnessing();
                        });
                    });
                }, function(e) { // 拍照错误
                    _this.$emit('cancelPhoto');
                    _this.signOut(true);
                });
            } catch (err) {
                // alert('请使用手机操作');
            }
        },
        compressImage(url, filename) {
            let _this = this;
            const plus = _this.$store.state.config.plus ? _this.$store.state.config.plus : window.plus;
            return new Promise((resolve, reject) => {
                var name = '_doc/upload/' + filename;
                plus.zip.compressImage(
                    {
                        src: url, //src: (String 类型 )压缩转换原始图片的路径
                        dst: name, //压缩转换目标图片的路径
                        quality: 90, //quality: (Number 类型 )压缩图片的质量.取值范围为1-100
                        overwrite: true, //overwrite: (Boolean 类型 )覆盖生成新文件
                        width: '250',
                        height: '320'
                    },
                    function(zip) {
                        //页面显示图片
                        // showPics(zip.target, name);
                        console.log(zip, 'zip');
                        resolve(zip);
                    },
                    function(error) {
                        console.log(error, 'error');
                        reject(error);
                        // plus.nativeUI.toast("压缩图片失败，请稍候再试");
                    }
                );
            });
        },
        // 转base64
        showPics(url, name) {
            let _this = this;
            return new Promise((resolve, reject) => {
                //根据路径读取到文件
                _this.$store.state.config.plus.io.resolveLocalFileSystemURL(url, function(entry) {
                    entry.file(function(file) {
                        var fileReader = new _this.$store.state.config.plus.io.FileReader();
                        fileReader.readAsDataURL(file);
                        fileReader.onloadend = function(e) {
                            var picUrl = e.target.result.toString();
                            resolve(picUrl);
                        };
                    });
                });
            });
        },
        // 打开摄像头
        openPhoto() {
            this.screenWidth = window.outerWidth;
            this.clientHeight = window.outerHeight;
            this.$nextTick(() => {
                this.video = document.getElementById('video');
                this.canvas = document.getElementById('canvas');
                this.context = this.canvas.getContext('2d');
                let constraints = {
                    audio: false,
                    video: {width: this.screenWidth, height: this.clientHeight, facingMode: 'user'}
                };
                const promise = navigator.mediaDevices.getUserMedia(constraints); // h5 新的API\
                const _this = this;
                promise.then(function(MediaStream) {
                    _this.video.srcObject = MediaStream;
                    _this.video.play();
                }).catch(function(PermissionDeniedError) {
                    console.log(PermissionDeniedError);
                });
            });
        },
        // 开始拍照
        startPhoto() {
            // 点击，canvas画图
            this.context.translate(this.screenWidth * 0.5, this.clientHeight * 0.5);
            this.context.scale(-1, 1);//镜像翻转
            this.context.drawImage(this.video, -this.screenWidth / 2, -this.clientHeight / 2, this.screenWidth, this.clientHeight);
            // 获取图片base64链接
            this.imgSrc = this.canvas.toDataURL('image/png');
            const blob = this.dataURLtoBlob(this.imgSrc);
            const toFlie = new File([blob], 'qiangzi.png', { type: blob.type, lastModified: Date.now() });
            const formData = new FormData();
            formData.append('file', toFlie);
            this.$axios.post('/app/api/file', formData).then(res => {
                this.url = res.data.url;
                // 这里进行抓拍回显，重新拍摄按钮
                this.capImagesUrl = this.appUrl + this.url;
                // this.sumitErrorTips = true;
                this.surePhoto();
            });
        },
        // 安卓回显后，点击确定
        async surePhoto() {
            this.witnessing();
        },
        // 抓拍
        witnessing() {
            if (this.isiOS) {
                this.isPhoto = false;
                this.$emit('witnesState', false, this.capImagesUrl, this.imgSrc);
            } else {
                this.isPhoto = false;
                this.sumitErrorTips = false;
                this.stopNavigator();
                this.$emit('witnesState', false, this.capImagesUrl, this.imgSrc);
            }
        },
        // 退出人脸抓拍
        signOut(val) {
            this.$emit('changeState', false);
            if (val !== true) {
                this.stopNavigator();
            }
        },
        // 关闭摄像头
        stopNavigator() {
            if (this.video && this.video !== null) {
                this.video.srcObject.getTracks()[0].stop();
            }
            // this.clearCanvas('canvasCamera')
        },
        // base64转blob
        dataURLtoBlob(dataurl) {
            var arr = dataurl.split(',');
            var mime = arr[0].match(/:(.*?);/)[1];
            var bstr = atob(arr[1]);
            var n = bstr.length;
            var u8arr = new Uint8Array(n);
            while (n--) {
                u8arr[n] = bstr.charCodeAt(n);
            }
            return new Blob([u8arr], { type: mime });
        }
    }

};
</script>

<style lang="less" scoped>
.photo-tips{
    position: absolute;
    top: 28%;
    border-radius: 5px;
}
.photo-start{
    position: absolute;
    top: 0;
}

.overlly{
   z-index: 999;
}
/deep/.van-button--normal{
    font-size: 14px;
    width: 112px;
    height: 36px;
    border-radius: 3px;
  }
  .buuton-footer{
    // display: flex;
    // justify-content: space-around ;
    margin-bottom: 15px;
    padding: 15px 0;
    position: absolute;
    bottom: 30px;
    width: 100%;
    .button-div{
      display: flex;
      justify-content: center;
    }
    /deep/.van-button--info{
        background-color: #075ebb;
        border: 1px solid #075ebb;
    }
  }
  .title-photo{
    font-size: 20px;
    padding: 12px;
    border-bottom: 1px solid #C3C3C3;
  }
</style>>
